package com.frank.service.test4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: huweifeng
 * @Date: 2024/12/13
 * @Description: NIO创建server
 * 阻塞
 **/
@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        // 0.创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(16);
        // 1.创建服务端
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 2.绑定端口
        ssc.bind(new InetSocketAddress(8090));
        // 3.连接集合
        List<SocketChannel> channels = new ArrayList<>();
        while (true) {
            log.debug("connecting...");
            // 4.接受客户端的连接
            SocketChannel sc = ssc.accept(); // 阻塞方法
            log.debug("connect...{}",sc);
            channels.add(sc);
            for (SocketChannel channel : channels) {
                // 5.接收消息
                log.debug("before read...{}", channel);
                channel.read(buffer); // 阻塞方法，线程停止运行
                buffer.flip(); // 切换为读模式
                buffer.clear(); // 切换为写模式
                log.debug("after read...{}", channel);
            }
        }
    }
}
